package com.cxx.purchasecharge.component.controller.usersecurity;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.bean.PCApplicationContext;
import com.cxx.purchasecharge.component.bean.usersecurity.AuthorityBean;
import com.cxx.purchasecharge.component.bean.usersecurity.RoleBean;
import com.cxx.purchasecharge.component.controller.GenericController;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.BeanConvertUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.Role;
import com.cxx.purchasecharge.dal.RoleDao;

@Controller
@RequestMapping ("/role")
public class RoleManager extends GenericController<RoleBean>
{
    private static final Logger logger = Logger.getLogger (RoleManager.class);

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PCApplicationContext pcContext;
    
    public RoleManager () 
    {
        super.setViewName("roleManagement");
    }

    @Override
    public String checkExist(@RequestParam String roleId, @RequestParam String name, HttpServletRequest request)
    {
        if (StringUtils.isBlank (roleId))
        {
            // new
            Role obj = roleDao.findByName (name);
            if (null != obj)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long uid = Long.parseLong (roleId);
            Role role = roleDao.findByName (name);
            if (null != role && role.getId () != uid)
            {
                return "false";
            }
        }

        return "true";
    }

    @Override
    public String getAllModel(DataGridRequestForm dataGridRequestForm, HttpServletRequest request)
    {
        List <Role> roles = (List <Role>) roleDao.findAll ();

        JSONArray jsonArray = JSONArray.fromObject (BeanConvertUtils.roleList2RoleBeanList (roles));
        return jsonArray.toString ();
    }

    @Override
    public String addModel(RoleBean bean, BindingResult bindingResult, HttpServletRequest request)
    {
        preprocessRole (bean, request);
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                roleDao.save (BeanConvertUtils.roleBean2Role (bean));
                pcContext.getSecurityResourceMap(true);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                                       ComponentConstants.MSG_ROLE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                       ComponentConstants.MSG_ROLE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @Override
    public String updateModel(RoleBean bean, BindingResult bindingResult, HttpServletRequest request)
    {
        preprocessRole (bean, request);
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                roleDao.save (BeanConvertUtils.roleBean2Role (bean));
                pcContext.getSecurityResourceMap(true);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_ROLE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_FAIL,
                                                                                       ComponentConstants.MSG_ROLE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @Override
    public String deleteModels(@RequestParam String ids, HttpServletRequest request)
    {
        if (null != ids && ids.trim ().length () > 0)
        {
            Role role;
            List <Role> roles = new ArrayList <Role> ();
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                for (String id : idArr)
                {
                    role = new Role ();
                    role.setId (Long.parseLong (id));
                    roles.add (role);
                }
            }
            else
            {
                role = new Role ();
                role.setId (Long.parseLong (ids));
                roles.add (role);
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                roleDao.delete (roles);
                pcContext.getSecurityResourceMap(true);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_ROLE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_FAIL,
                                                                                       ComponentConstants.MSG_ROLE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST);
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }

    private void preprocessRole (RoleBean roleBean, HttpServletRequest request)
    {
        String authorities = request.getParameter ("authorities");
        if (StringUtils.isNotBlank (authorities))
        {
            List <AuthorityBean> authBeans = new ArrayList <AuthorityBean> ();
            AuthorityBean authorityBean = null;
            String[] authArr = authorities.split (",");
            for (String authId : authArr)
            {
                authorityBean = new AuthorityBean ();
                authorityBean.setId (authId);
                authBeans.add (authorityBean);
            }
            roleBean.setAuthorityBeans (authBeans);
        }
    }

}
